﻿function OnSuccess() {

}
function OnBegin() {
    $.BigLoading();
}
function OnComplete() {
    $.RemoveBigLoading();
}
function OnFailure() {
    if ($('#overlay').length > 0) {
        $.RemoveBigLoading();
    }
    alert('Lỗi hệ thống. Vui lòng thông báo cho bộ phận quản trị.');
}

/*
nStr: The number to be formatted, as a string or number. No validation is done, so don't input a formatted number. If inD is something other than a period, then nStr must be passed in as a string.
inD: The decimal character for the input, such as '.' for the number 100.2
outD: The decimal character for the output, such as ',' for the number 100,2
sep: The separator character for the output, such as ',' for the number 1,000.2 
*/
function addSeparatorsNF(nStr, inD, outD, sep) {
    nStr += '';
    var dpos = nStr.indexOf(inD);
    var nStrEnd = '';
    if (dpos != -1) {
        nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
        nStr = nStr.substring(0, dpos);
    }
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '$1' + sep + '$2');
    }
    return nStr + nStrEnd;
}

/*http://www.mredkj.com/javascript/nfbasic.html*/
function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}




$(function () {
    jQuery.fn.extend({

        outerHtml: function (replacement) {
            // We just want to replace the entire node and contents with
            // some new html value
            if (replacement) {
                return this.each(function () { $(this).replaceWith(replacement); });
            }

            /*
            * Now, clone the node, we want a duplicate so we don't remove
            * the contents from the DOM. Then append the cloned node to
            * an anonymous div.
            * Once you have the anonymous div, you can get the innerHtml,
            * which includes the original tag.
            */
            var tmp_node = $("<div></div>").append($(this).clone());
            var markup = tmp_node.html();

            // Don't forget to clean up or we will leak memory.
            tmp_node.remove();
            return markup;
        }
    });

    $.fn.vCenter = function (options) {
        var pos = {
            sTop: function () {
                return window.pageYOffset
        || document.documentElement && document.documentElement.scrollTop
        || document.body.scrollTop;
            },
            wHeight: function () {
                return window.innerHeight
        || document.documentElement && document.documentElement.clientHeight
        || document.body.clientHeight;
            }
        };
        return this.each(function (index) {
            if (index == 0) {
                var $this = $(this);
                var elHeight = $this.height();
                var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2) - options.offsetTop;
                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: elTop
                });
            }
        });
    };

    $.BigLoading = function () {

        var overlayElement = $("<div id='overlay' class='ui-widget-overlay'></div>");
        /*
        var loadingtag = '<object width="200" height="100">'
            + '<param name="movie" value="' + swfFile + '">'
            + '<embed src="' + BOSettings.Url.Base.ImageRoot + '/loading/loading10.swf' + '" width="200" height="100"></embed>'
            + '</object>'
        */

        var loadingtag = '<a href="javascript:$.RemoveBigLoading();"><img src="/Content/Images/loading/cafe.gif' + '" width="100" height="100" /></a>';

        var loadingElement = $('<div id="bigLoadingElement">'
            + loadingtag
            + '</div>'
            );
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var popupWidth = 100;
        loadingElement.css({
            "position": "absolute",
            "left": windowWidth / 2 - popupWidth / 2,
            "z-index": 2000
        });
        overlayElement.css({
            "width": $(document).width(),
            "height": $(document).height(),
            "z-index": 1500
        });
        loadingElement.vCenter({ offsetTop: 100 });
        overlayElement.appendTo("body");
        loadingElement.appendTo("body");

    };

    $.RemoveBigLoading = function () {
        $("#bigLoadingElement").remove();
        $("#overlay").remove();
    };

    $.HtmlEncode = function (html) {
        if (html == null)
            return "";
        return $('<div/>').text(html).html();
    };

    $.HtmlDecode = function (text) {
        if (html == null)
            return "";
        return $('<div/>').html(text).text();
    };
});




function showDialogNotification(message, type, enableAnimation, autoHide) {

    if (enableAnimation == null)
        enableAnimation = true;

    if (autoHide == null)
        autoHide = true;

    if (message == null)
        message = 'Cập nhật thành công';


    $(".Notification").text(message);

    // prepare style and effect
    $(".Notification").removeClass('ui-state-error');
    $(".Notification").addClass('ui-corner-all');
    if (type == 'error') {
        $(".Notification").addClass('ui-state-error');
        if (enableAnimation) {
            $('.Notification').effect('shake', { times: 3, distance: 10 }, 'slow');
            //        $('.Notification').effect("highlight", { times: 100}, 100);    
        }

    }
    else {
        $(".Notification").addClass('ui-state-highlight');
    }

    $(".Notification").show();

    $(".Notification").parents("div.Dialog").dialog("option", { height: 'auto' });
    if (autoHide) {
        setTimeout(hideDialogNotification, 10000);
    }

}

function hideDialogNotification() {
    $(".Notification").fadeOut(function () {
        $(this).parent("div.Dialog").dialog("option", { height: 'auto' });
    });

}

jQuery.fn.ForceNumericOnly =
    function () {
        return this.each(function () {
            $(this).keydown(function (e) {
                var key = e.charCode || e.keyCode || 0;
                // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
                return (
                    key == 13 || //enter key
                    key == 8 ||
                    key == 9 ||
                    key == 46 ||
                    (key >= 37 && key <= 40) ||
                    (key >= 48 && key <= 57) ||
                    (key >= 96 && key <= 105));
            });
        });

    };
$.FormatNumber = function (obj) {

    var strvalue;
    if (eval(obj))
        strvalue = eval(obj).value;
    else
        strvalue = obj;
    var num;
    num = strvalue.toString().replace(/\$|\./g, '');
    //debugger;
    if (isNaN(num)) {
        //e.preventDefault();
        return false;
    }
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    num = Math.floor(num / 100).toString();
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.' +
            num.substring(num.length - (4 * i + 3));
    //return (((sign)?'':'-') + num);
    //removeInValid(obj);
    return eval(obj).value = (((sign) ? '' : '-') + num);
};

function FormatNumber(strvalue) {
    var num = strvalue.toString().replace(/\$|\./g, '');

    if (isNaN(num))
        num = "";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    num = Math.floor(num / 100).toString();
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.' +
num.substring(num.length - (4 * i + 3));
    //return (((sign)?'':'-') + num);
    //removeInValid(obj);
    return eval(strvalue).value = (((sign) ? '' : '-') + num);
}

function num2money(n_value) {
    // validate input
    if (isNaN(Number(n_value)))
        return 'ERROR';

    // save the sign
    var b_negative = Boolean(n_value < 0);

    n_value = Math.abs(n_value);

    // round to 1/100 precision, add ending zeroes if needed
    var s_result = String(Math.round(n_value * 1e2) % 1e2 + '00').substring(0, 2);

    // separate all orders
    var b_first = true;

    var s_subresult;

    while (n_value > 1) {

        s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);

        s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;

        b_first = false;

        n_value = n_value / 1e3;

    }

    // add at least one integer digit

    if (b_first)
        s_result = '0.' + s_result;


    // apply formatting and return

    return b_negative ? '-' + s_result : s_result;

}

$.genarateDictionary = function (key, value, character) {
    /*  if (key.indexOf(character) < 0 || value.indexOf(character) < 0) {
          return "";
      }*/
    var keys = key.split(character);
    var values = value.split(character);
    if (keys.length != values.length)
        return "";
    var dictionary = [];
    for (var i = 0; i < keys.length; i++) {
        dictionary[keys[i].toString()] = values[i];
    }

    return dictionary;
};


function ValidationAndSubmitForm(elementId) {

    $('#' + elementId).submit();
    $('#' + elementId).submit(function () {
        alert(1);
        var isValid = true;
        $('#GetRequestListForm input[data-val="true"]').each(function (index, e) {
            var element = $(e);
            var attr = $(e).attr('data-val-type');
            var dataRequire = $(e).attr('data-require');
            var val = $(e).val().trim();
            var erroclass = "input-validation-error";
            alert(dataRequire);
            if (dataRequire && val == "") {
                element.addClass(erroclass);
                isValid = false;
            }
            else if (attr == 'numberInt' && !val.match(/[0-9 -()+]+$/)) {
                element.addClass(erroclass);
                isValid = false;
            }
            else if (attr == 'numberFloat' && !val.match('[-+]?([0-9]*\.[0-9]+|[0-9]+)')) {
                element.addClass(erroclass);
                isValid = false;
            }
            else if (attr == 'email' && !val.match('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$')) {
                element.addClass(erroclass);
                isValid = false;
            }
            else if (attr == 'date' && !(val.match('^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$') || val.match('^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$'))) {
                element.addClass(erroclass);
                isValid = false;
            }
        });

        alert(isValid);

        if (isValid == false) {
            return false;
        }
    });

}

function registerEvent_NumbersOnly() {
    //$(document).on('keydown', '.numbersonly', function (e) {
    $('.numbersonly').live('keydown', function (e) {
        var code = e.keyCode;
        if (code >= 96 && code <= 105 || code >= 48 && code <= 57 || code == 13 || code == 9 || code == 8 || code == 46)// TenKey0-9_Check || Main0-9_Check || ENTER_Check || TAB_Check || BACKSPACE_Check 
            return true;
        else {
            // Prevent the normal behavior since we use a dialog
            e.preventDefault();
            return false;
        }
    });
}

function registerEvent_FloatOnly() {
    //$(document).on('keydown', '.numbersonly', function (e) {

    $('.floatonly').live('keydown', function (e) {
        var code = e.keyCode;

        if (code >= 96 && code <= 105 || code >= 48 && code <= 57 || code == 13 || code == 9 || code == 8 || code == 188 || code == 46)// TenKey0-9_Check || Main0-9_Check || ENTER_Check || TAB_Check || BACKSPACE_Check 
            return true;
        else {
            // Prevent the normal behavior since we use a dialog
            e.preventDefault();
            return false;
        }
    });
}

function registerEvent_Money() {
    $('.money').live('keydown', function (e) {
        var code = e.keyCode;
        //alert(code)
        if (code >= 96 && code <= 105 || code >= 48 && code <= 57 || code == 13 || code == 9 || code == 8 || code == 16 || code == 35 || code == 36 || code == 37 || code == 39 || code == 46) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    }).live("keyup", function (e) {
        var code = e.keyCode;
        //alert(code);
        if (code == 9 || code == 8 || code == 16 || code == 35 || code == 36 || code == 37 || code == 39 || code == 46) return true;

        var strvalue = $(this).val();
        var num;
        num = strvalue.toString().replace(/\$|\./g, '');

        var sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        num = Math.floor(num / 100).toString();
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++) {
            num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
        }
        var result = (((sign) ? '' : '-') + num);
        $(this).val(result);
    });
}

//Tu
$.urlParams = function () {
    var queryParameters = {}, queryString = location.search.substring(1),
        re = /([^&=]+)=([^&]*)/g, m;

    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURI(m[2]).replace(/\+/g, " ");
    }
    return queryParameters;
};

function ReplaceStaticInformation() {
    $(".ThanhPho").each(function () {
        if ($(this).text() == '')
            return;
        var ID = parseInt($(this).text());
        var data = jQuery.grep(staticInfo.cityList, function (item, index) {
            return (item.ID == ID);
        });

        if (data.length > 0) {
            $(this).html(data[0].Name);
        }

    });

    $(".QuanHuyen").each(function () {
        if ($(this).text() == '')
            return;
        var ID = parseInt($(this).text());

        var data = jQuery.grep(staticInfo.districtList, function (item, index) {
            return (item.ID == ID);
        });

        if (data.length > 0) {
            $(this).html(data[0].Name);
        }
    });

    $(".PhuongXa").each(function () {
        if ($(this).text() == '')
            return;

        var ID = parseInt($(this).text());
        var data = jQuery.grep(staticInfo.wardList, function (item, index) {
            return (item.ID == ID);
        });

        if (data.length > 0) {
            $(this).html(data[0].Name);
        }
    });

    $(".Tuyen").each(function () {
        if ($(this).text() == '')
            return;

        var ID = parseInt($(this).text());

        var data = jQuery.grep(staticInfo.routeList, function (item, index) {
            return (item.ID == ID);
        });
        if (data.length > 0) {
            $(this).html(data[0].Name);
        }
    });

    $(".Kho").each(function () {
        if ($(this).text() == '')
            return;

        var ID = parseInt($(this).text());
        var data = jQuery.grep(staticInfo.cityList, function (item, index) {
            return (item.ID == ID);
        });
        if (data.length > 0) {
            $(this).html(data[0].Name);
        }
    });
}

function scrollTable() {
    $('table.scrollable').each(function () {

        var table = $(this);

        var len = table.find('th').length;
        var widthArray = new Array(table.find('th').length);
        var paddingLeft = new Array(table.find('th').length);
        var paddingRight = new Array(table.find('th').length);

        // set fix width 
        $('th', table.find('thead')).each(function (index) {
            widthArray[index] = $(this).width();
            paddingLeft[index] = $(this).css('padding-left');
            paddingRight[index] = $(this).css('padding-right');

            $(this).width(widthArray[index]);
            //$(this).css('padding-left',paddingLeft[index]);
            //$(this).css('padding-right', paddingRight[index]);
        });

        // set fix width 
        $('tr td', table.find('tbody')).each(function (index) {
            $(this).width(widthArray[index % len]);
            $(this).css('padding-left', paddingLeft[index % len]);
            $(this).css('padding-right', paddingRight[index % len]);
        });

        // make scroll
        table.find('thead, tbody').css('display', 'block');
        table.find('tbody')
            .css('max-height', '500px')
            .css('overflow-y', 'auto');

        // re-posittion dialog if have one
        $('#dialog').dialog('option', 'position', 'center');

    });



}

$(function () {
    ReplaceStaticInformation();

});

function RoundNumber(number) {
    return Math.round(parseFloat(number));
}

Number.prototype.formatMoney = function (decPlaces, thouSeparator, decSeparator) {
    var n = this,
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
    decSeparator = decSeparator == undefined ? "." : decSeparator,
    thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
    sign = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

function htmlEncode(value) {
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}